const path = require('path');
const ora = require('ora').default || require('ora');

// 导入编译后的 TypeScript 模块
const { IconifyAnalyzer } = require('../../dist/analyzers/iconifyAnalyzer');
const { IconifyDataGenerator } = require('../../dist/generators/iconifyDataGenerator');

/**
 * Iconify 图标分析命令
 */
async function handleIconifyCommand(directory, options) {
  const spinner = ora('正在分析 Iconify 图标...').start();

  try {
    // 解析目录路径
    const targetDir = path.resolve(directory);

    // 创建分析器和生成器
    const analyzer = new IconifyAnalyzer();
    const generator = new IconifyDataGenerator();

    // 执行分析
    spinner.text = `正在扫描目录: ${targetDir}`;
    const analysisStats = await analyzer.analyzeDirectory(targetDir, {
      recursive: options.recursive,
      outputFormat: options.format,
      generateTypes: options.types
    });

    if (analysisStats.totalIcons === 0) {
      spinner.warn('未找到任何 Iconify 图标');
      return;
    }

    // 生成数据文件
    spinner.text = '正在生成图标数据文件...';
    const outputOptions = {
      outputDir: options.outputDir || path.join(targetDir, 'data'),
      fileName: options.output || 'iconify',
      format: options.format || 'js',
      generateTypes: options.types !== false,
      includeStats: options.stats !== false,
      esm: options.esm !== false,
      minify: options.minify === true,
      generateImports: options.format === 'imports-only' ? true : options.imports !== false
    };

    const result = await generator.generate(analysisStats, outputOptions);

    spinner.succeed(`Iconify 分析完成！生成了 ${result.files.length} 个文件:`);

    result.files.forEach(file => {
      console.log(`  - ${path.relative(process.cwd(), file)}`);
    });

    // 显示简要统计
    console.log(`\n📊 统计信息:`);
    console.log(`  - 总图标数量: ${analysisStats.totalIcons}`);
    console.log(`  - 图标集合数量: ${analysisStats.collections.size}`);
    console.log(`  - 总使用次数: ${analysisStats.totalUsage}`);
    console.log(`  - 涉及文件数: ${analysisStats.filesWithIcons}/${analysisStats.totalFiles}`);

    // 显示热门图标集合
    console.log(`\n🔥 热门图标集合:`);
    const sortedCollections = Array.from(analysisStats.collections.entries())
      .sort(([, a], [, b]) => b.size - a.size)
      .slice(0, 5);

    sortedCollections.forEach(([prefix, icons]) => {
      console.log(`  - ${prefix}: ${icons.size} 个图标`);
    });

  } catch (error) {
    spinner.fail(`Iconify 分析失败: ${error.message}`);
    process.exit(1);
  }
}

module.exports = { handleIconifyCommand };